﻿<%@ WebHandler Language="C#" Class="organizationManage" %>

using System;
using System.Text;
using System.Web;
using System.Data;
using System.Collections.Generic;
using Chenxin.Lib.Utility;

public class organizationManage : AjaxHandlerBase
{

    //hejifeng 010406 Add Start
    public organizationManage()
    {
        //部门删除
        htTypePermit.Add("DelDepart", Constants.Permit_NodeDel);
        htTypePermit.Add("hasChild", Constants.Permit_NodeDel);
        //部门迁移
        htTypePermit.Add("move", Constants.Permit_NodeMove);
        //部门编辑
        htTypePermit.Add("GetDepartInfo", Constants.Permit_NodeEdit);
        //部门添加
        htTypePermit.Add("add", Constants.Permit_NodeAdd);
        //部门人员添加
        htTypePermit.Add("addUser", Constants.Permit_UserInfoSet);
        //部门人员删除
        htTypePermit.Add("delUser", Constants.Permit_DepartUserDel);
        //密码重置
        htTypePermit.Add("ResetPws", Constants.Permit_PasswordReset);

    }
    //hejifeng 010406 Add End

    private Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);

    override public void RequestProcess(HttpContext context)
    {

        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        

        //处理类型
        string strDealType = context.Request.Params["op"];

        switch (strDealType)
        {
            case "GetRegion":       //得到区域数据
                getAllRegions(context);
                break;
            case "GetTree":         //得到组织结构树形
                getDepartTree(context);
                break;
            case "GetDepartInfo":   //得到部门数据
                getDepartInfo(context);
                break;
            case "edit":            //编辑部门
                editDepart(context);
                break;
            case "hasChild":        //判断是否有子节点或隶属人员
                hasChildDepart(context);
                break;
            case "DelDepart":       //删除部门
                delDepart(context);
                break;
            case "GetUsersInfo":    //得到部门中人员的业务数据
                getUsersInfo(context);
                break;
            case "ResetPws":        //密码重置
                resetPassword(context);
                break;
            case "addUser":         //添加人员业务权限
                addUser(context);
                break;
            case "namecheck":       //验证名称
                NameCheck(context);
                break;
            case "codecheck":       //验证编号
                CodeCheck(context);
                break;
            case "add":             //添加部门
                AddDep(context);
                break;
            case "initSelect":      //下拉框数据    
                initSelect(context);
                break;
            case "searchDep":       //根据查询条件得到部门总数
                searchDep(context);
                break;
            case "pageShow":        //分页显示部门
                pageShow(context);
                break;
            case "delUser":         //删除人员业务权限
                delUser(context);
                break;
            case "move":            //节点转移
                moveDep(context);
                break;
            case "GetRole":         //得到全部角色
                getRole(context);
                break;
            case "getSel":          //级联下拉框查询
                getSel(context);
                break;
            case "local":           //设置业务所属地
                setLocal(context);
                break;
            case "GetDepartSetting":    //得到部门参数数据
                getDepartSetting(context);
                break;
            case "usercodecheck":       //员工工号验证
                getUserByCode(context);
                break;
            case "getTermsSetting":     //得到部门默认业务权限
                getTermsSetting(context);
                break;
            case "opTermsSetting":      //增加或更新部门参数设定
                opTermsSetting(context);
                break;
            default:
                break;
        }

    }

    //增加或更新部门参数设定
    private void opTermsSetting(HttpContext context)
    {
        string depid = context.Request.Params["departid"];
        string terms = context.Request.Params["terms"];
        string setting = "";
        string str_setting = "";
        if (!string.IsNullOrEmpty(context.Request.Params["setting"]))
        {
            setting = context.Request.Params["setting"];
            string[] array = setting.Split(',');
            for (int i = 0; i < array.Length; i++)
            {
                str_setting += "'1',";
            }
            str_setting = str_setting.Substring(0, (str_setting.Length - 1));
        }
        string strSql = "";
        strSql += string.Format("delete HR_Rel_Purview where DepartID='{0}' and TermsName='{1}';", depid, terms);
        strSql += string.Format("insert into HR_Rel_Purview(RecodID,DepartID,TermsName,{0},Addtime) values(newid(),'{1}','{2}',{3},getdate());", setting, depid, terms, str_setting);

        try
        {
            Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);
            context.Response.Write("{success:'1'}");
        }
        catch (Exception ex)
        {
            context.Response.Write("{success:'0',txt:'" + ex.Message + "'}");
        }
    }


    //根据部门ID得到部门参数设定
    private void getTermsSetting(HttpContext context)
    {
        string depid = context.Request.QueryString["departid"];
        string terms = context.Request.QueryString["terms"];
        string strSql = string.Format("DepartID='{0}' and TermsName='{1}' ", depid, terms);
        List<Chenxin.Lib.Hr.Entity.HR_Rel_Purview> list = Chenxin.Lib.Hr.DAL.HR_Rel_Purview.GetListArray(strSql);
        if (list.Count > 0)
        {
            StringBuilder strb = new StringBuilder();
            strb.Append("{success:'1',data:{");
            strb.Append("ViewPubHouse:'" + list[0].ViewPubHouse.ToString() + "'");
            strb.Append(",ViewPrivHouse:'" + list[0].ViewPrivHouse.ToString() + "'");
            strb.Append(",ViewHideHouse:'" + list[0].ViewHideHouse.ToString() + "'");
            //strb.Append(",ViewPubDemand:'" + list[0].ViewPubDemand.ToString() + "'");
            strb.Append(",ViewPrivDemand:'" + list[0].ViewPrivDemand.ToString() + "'");
            strb.Append(",ViewRealCustomer:'" + list[0].ViewRealCustomer.ToString() + "'");
            strb.Append(",ViewFakeCustomer:'" + list[0].ViewFakeCustomer.ToString() + "'");
            strb.Append(",EditPrimaryHouse:'" + list[0].EditPrimaryHouse.ToString() + "'");
            strb.Append(",EditNormalHouse:'" + list[0].EditNormalHouse.ToString() + "'");
            //strb.Append(",EditCustomer:'" + list[0].EditCustomer.ToString() + "'");
            strb.Append(",DelTrace:'" + list[0].DelTrace.ToString() + "'");
            strb.Append(",CanProtect:'" + list[0].CanProtect.ToString() + "'");
            strb.Append(",CanLockHouse:'" + list[0].CanLockHouse.ToString() + "'");
            strb.Append(",ViewLockHouse:'" + list[0].ViewLockHouse.ToString() + "'");
            //strb.Append(",CanChangeApp:'" + list[0].CanChangeApp.ToString() + "'");
            strb.Append(",ViewChange:'" + list[0].ViewChange.ToString() + "'");
            strb.Append(",CanChangeConfirm:'" + list[0].CanChangeConfirm.ToString() + "'");
            strb.Append(",ViewEntrust:'" + list[0].ViewEntrust.ToString() + "'");
            strb.Append(",CanCancelTrust:'" + list[0].CanCancelTrust.ToString() + "'");
            strb.Append(",UnCancelTrust:'" + list[0].UnCancelTrust.ToString() + "'");
            strb.Append(",CanDelTrust:'" + list[0].CanDelTrust.ToString() + "'");
            //strb.Append(",CanDoTask:'" + list[0].CanDoTask.ToString() + "'");
            strb.Append("}}");
            context.Response.Write(strb.ToString());
        }
        else
            context.Response.Write("{success:'0'}");
    }


    //根据用户工号得到用户信息
    private void getUserByCode(HttpContext context)
    {
        string usercode = context.Request.QueryString["usercode"];
        Chenxin.Lib.Passport.Entity.Hr_UserInfo userinfo = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityByCode(usercode);
        if (userinfo != null)
            context.Response.Write("{success:'1',txt:'" + userinfo.UserName + "(" + userinfo.BelongDepart + ")',id:'" + userinfo.UserId + "'}");
        else
            context.Response.Write("{success:'0',txt:'工号：" + usercode + "不存在！'}");
    }


    //得到部门参数
    private void getDepartSetting(HttpContext context)
    {
        string DepartId = context.Request.QueryString["DepartId"];
        StringBuilder strb = new StringBuilder();
        
        string strKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPART_SETTINGS, DepartId);
        Chenxin.Lib.House.Entity.House_BusinessSetting ds;
        ds = cs.GetObject(strKey) as Chenxin.Lib.House.Entity.House_BusinessSetting;
        if (!cs.Hit||ds==null)
        {
            ds = Chenxin.Lib.House.DAL.House_BusinessSetting.GetModel(new Guid(DepartId));
            if (ds != null) cs.Set(strKey, ds);
        }
        
        
        //if (ds!=null)
        //{
        //    DataTable dt = ds.Tables[0];
        //    DataRow dr = dt.Rows[0];
        //    strb.Append("[{DepartId:'" + dr["DepartId"].ToString() + "' ,ProtectedNum:'" + dr["ProtectedNum"].ToString() + "',ViewOwnerNum:'" + dr["ViewOwnerNum"].ToString());
        //    strb.Append("',IsHideHouse: '" + dr["IsHideHouse"].ToString());
        //    strb.Append("',IsAloneUserCode: '" + dr["IsAloneUserCode"].ToString());
        //    strb.Append("',LockHouseDay: '" + dr["LockHouseDay"].ToString());
        //    strb.Append("',IsProtectMark: '" + dr["IsProtectMark"].ToString());
        //    strb.Append("',MarkProtectHours: '" + dr["MarkProtectHours"].ToString());
        //    strb.Append("',AllowPrivHouse: '" + dr["AllowPrivHouse"].ToString());
        //    strb.Append("',AllowPrivDemand: '" + dr["AllowPrivDemand"].ToString());
        //    strb.Append("',IsUseBlacklist: '" + dr["IsUseBlacklist"].ToString());
        //    strb.Append("',BlacklistLevel: '" + dr["BlacklistLevel"].ToString());
        //    strb.Append("',CanAddAtCityId: '" + dr["CanAddAtCityId"].ToString());
        //    strb.Append("',CanAddAtCityName: '" + dr["CanAddAtCityName"].ToString());
        //    strb.Append("'}]");
        //}
        context.Response.Write("["+Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds)+"]");
    }


    //设置业务所属地
    private void setLocal(HttpContext context)
    {
        //工号
        string usercode = context.Request.Params["usercode"];
        //城市ID
        string cityid = context.Request.Params["cityid"];
        //城市
        string city = context.Request.Params["city"];
        //公司ID
        string companyid = context.Request.Params["companyid"];
        //公司
        string company = context.Request.Params["company"];
        //部门ID
        string depid = context.Request.Params["depid"];
        //部门
        string dep = context.Request.Params["dep"];

        string strSql = string.Format("update Hr_UserInfo set CityId='{0}',CityName='{1}',CompanyId='{2}',CompanyName='{3}',DepartId='{4}',DepartName='{5}' where UserCode='{6}'", cityid, city, companyid, company, depid, dep, usercode);
        bool flag = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);
        if (flag)
            context.Response.Write("{success:'1'}");
        else
            context.Response.Write("{success:'0',txt:'工号：" + usercode + "不存在！'}");
    }

    //得到下拉框数据
    private void getSel(HttpContext context)
    {
        string cityid = "";
        string strSql = "";
        if (!string.IsNullOrEmpty(context.Request.QueryString["cityid"]))
        {
            cityid = context.Request.QueryString["cityid"];
        }
        if (cityid.Length < 1)
            strSql = string.Format("DepartProperty=100");
        else
        {
            if (cityid == "0")
            {
                cityid = Guid.Empty.ToString();

            }
            else if (cityid == "all")
            {
                strSql = "DepartProperty=200";
            }
            else
            {
                strSql = string.Format("DepartProperty=200 and CityId='{0}'", cityid);
            }
        }
        List<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo> deplist = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetListArray(strSql);

        //生成JSON字符串
        System.Text.StringBuilder str = new System.Text.StringBuilder();

        foreach (Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item in deplist)
        {
            str.Append(", { txt: '" + item.DepartName.Trim() + "', val: '" + item.DepartId.ToString() + "' }");
        }

        context.Response.Write(str.ToString());
    }

    //根据城市ID 得到所有角色
    private void getRole(HttpContext context)
    {
        string cityid = "";
        if (!string.IsNullOrEmpty(context.Request.QueryString["cityid"]))
        {
            cityid = context.Request.QueryString["cityid"];
        }
        string sql = string.Format("CityId='{0}'", cityid);

        List<Chenxin.Lib.Hr.Entity.Base_Permit_RoleDefine> rolelist = Chenxin.Lib.Hr.DAL.Base_Permit_RoleDefine.GetListArray(sql);

        System.Text.StringBuilder str = new System.Text.StringBuilder();

        foreach (Chenxin.Lib.Hr.Entity.Base_Permit_RoleDefine role in rolelist)
        {
            str.Append(string.Format("<input type='checkbox' value='{0}' />{1}", role.RoleId, role.RoleName));
        }
        context.Response.Write(str.ToString());
    }


    //转移门店
    private void moveDep(HttpContext context)
    {
        string id = "";     //部门ID
        string parentid = "";   //父节点ID
        string depname = "";    //部门名称
        if (!string.IsNullOrEmpty(context.Request.QueryString["id"]))
        {
            id = context.Request.QueryString["id"];
        }
        if (!string.IsNullOrEmpty(context.Request.QueryString["parentid"]))
        {
            parentid = context.Request.QueryString["parentid"];
        }
        if (!string.IsNullOrEmpty(context.Request.QueryString["depname"]))
        {
            depname = context.Request.QueryString["depname"];
        }
        string strSql = "";
        strSql += string.Format("delete Hr_Struct_DepartTreeRelation where ChildId='{0}';", id);
        strSql += string.Format("update Hr_DepartmentInfo set DepartSrc=(select DepartSrc from Hr_DepartmentInfo where DepartId='{0}')+DepartCode where DepartId='{1}';", parentid, id);
        strSql += string.Format("insert into Hr_Struct_DepartTreeRelation VALUES(newid(),'{0}','{1}');", parentid, id);
        //添加日志
        strSql += string.Format("insert into Hr_UserLogs values(newid(),'{0}','{1}','{2}','{3}','{4}','转移节点','{2}-转移节点:{5}',getdate());", id, CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, depname);
        try
        {
            Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);
            //context.Response.Write("{success:'1'}");

            //删除组织结构缓存
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_STRUCT_TREE, parentid);
            cs.Delete(strCacheKey); 
            
            context.Response.Write(retExecResult(Constants.ExecResult.Succ, "", ""));
        }
        catch (Exception ex)
        {
            //context.Response.Write("{success:'0',txt:'" + ex.Message + "'}");
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    //所在区域
    private void getAllRegions(HttpContext context)
    {
        string parentid = context.Request.Params["parentid"];

        string strsql = string.Format("DepartId='{0}'", parentid);
        string cityid = new Chenxin.Lib.Hr.BLL.Hr_DepartmentInfo().GetCityId(strsql);

        System.Collections.Generic.List<Chenxin.Lib.House.Entity.DataDictionary> dicList = new System.Collections.Generic.List<Chenxin.Lib.House.Entity.DataDictionary>();
        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.DICTDATA);
        string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.DICTDATA, "System.Region." + cityid);

        if (!cs.Hit)//若缓存未命中，则从数据库中获取并存入缓存，时间为1天
        {
            string strWhere = string.Format("CityId = '{0}' AND ItemKey = 'System.Region'", cityid);

            dicList = Chenxin.Lib.House.DAL.DataDictionary.GetListArray(strWhere, "ItemIndex");

            cs.Set(strCacheKey, dicList, DateTime.Today.AddDays(1));
        }


        //生成JSON字符串
        System.Text.StringBuilder str = new System.Text.StringBuilder();

        foreach (Chenxin.Lib.House.Entity.DataDictionary item in dicList)
        {
            str.Append(", { txt: '" + item.ItemValue.Trim() + "', val: '" + item.ItemIndex + "' }");
        }

        context.Response.Write(str.ToString());
    }

    //取得树结构    
    public void getDepartTree(HttpContext context)
    {
        context.Response.ContentType = "application/xhtml+xml";

        StringBuilder strTreeVal = new StringBuilder();
        Guid gdParentId;
        string strParentLevel = context.Request.Params["n_level"];
        string strParentId = context.Request.Params["nodeid"];
        string strParentLeft = context.Request.Params["n_left"];
        string strParentRight = context.Request.Params["n_right"];

        int intChildInc = 0;
        int intParentLeft;
        int intParentRigth;
        string strChildLevel;
        int intChildLeft;
        int intChildRight = 0;

        Chenxin.Lib.Hr.BLL.OrganizationManage bllOrgManage = new Chenxin.Lib.Hr.BLL.OrganizationManage();
        if (strParentId == null | strParentId == "")
        {
            gdParentId = Guid.Empty;
        }
        else
        {
            gdParentId = new Guid(strParentId.Replace(",", ""));
        }

        if (strParentLevel == null | strParentLevel == "")
        {
            strChildLevel = "0";
            intParentLeft = 0;
            intParentRigth = 100000000;
        }
        else
        {
            strChildLevel = (Convert.ToInt32(strParentLevel.Replace(",", "")) + 1).ToString();
            intParentLeft = Convert.ToInt32(strParentLeft.Replace(",", ""));
            intParentRigth = Convert.ToInt32(strParentRight.Replace(",", ""));
        }

        intChildRight = intParentLeft;

        List<Chenxin.Lib.Hr.Entity.Hr_Struct_DepartTreeRelation> lsDepartTree = bllOrgManage.Old_GetListByParentId(gdParentId);

        strTreeVal.Append("<?xml version='1.0' encoding='utf-8'?>");
        strTreeVal.Append("<rows><page>1</page><total>1</total><records>1</records>");

        if (strParentId == null | strParentId == "")
        {
            strTreeVal.Append("<row>");
            strTreeVal.Append("<cell>");
            strTreeVal.Append(Guid.Empty.ToString());
            strTreeVal.Append("</cell>");
            strTreeVal.Append("<cell>");
            strTreeVal.Append("易居臣信");
            strTreeVal.Append("</cell>");
            strTreeVal.Append("<cell>");
            strTreeVal.Append("0");
            strTreeVal.Append("</cell>");
            strTreeVal.Append("<cell>");
            strTreeVal.Append("0");
            strTreeVal.Append("</cell>");

            strTreeVal.Append("<cell>");
            strTreeVal.Append(strChildLevel);
            strTreeVal.Append("</cell>");

            strTreeVal.Append("<cell>");
            strTreeVal.Append(intParentLeft.ToString());
            strTreeVal.Append("</cell>");

            strTreeVal.Append("<cell>");
            strTreeVal.Append((intParentRigth + 1).ToString());
            strTreeVal.Append("</cell>");



            strTreeVal.Append("<cell>");
            strTreeVal.Append("false");
            strTreeVal.Append("</cell>");

            strTreeVal.Append("<cell>");
            strTreeVal.Append("false");
            strTreeVal.Append("</cell>");

            strTreeVal.Append("</row>");
        }
        else
        {
            if (lsDepartTree.Count != 0)
            {
                intChildInc = (intParentRigth - intParentLeft - 2) / lsDepartTree.Count;
            }

            for (int idxCnt = 0; idxCnt < lsDepartTree.Count; idxCnt++)
            {
                intChildLeft = intChildRight + 1;
                if (intChildRight + intChildInc < intParentRigth - 1)
                    intChildRight = intChildLeft + intChildInc;
                else
                    intChildRight = intParentRigth - 1;

                strTreeVal.Append("<row>");
                strTreeVal.Append("<cell>");
                strTreeVal.Append(lsDepartTree[idxCnt].ChildId.ToString());
                strTreeVal.Append("</cell>");
                strTreeVal.Append("<cell>");
                strTreeVal.Append(lsDepartTree[idxCnt].ChildName);
                strTreeVal.Append("</cell>");
                strTreeVal.Append("<cell>");
                strTreeVal.Append(lsDepartTree[idxCnt].ChildProperty);
                strTreeVal.Append("</cell>");
                strTreeVal.Append("<cell>");
                strTreeVal.Append(lsDepartTree[idxCnt].ChildCode);
                strTreeVal.Append("</cell>");

                strTreeVal.Append("<cell>");
                strTreeVal.Append(strChildLevel);
                strTreeVal.Append("</cell>");

                strTreeVal.Append("<cell>");
                strTreeVal.Append(intChildLeft.ToString());
                strTreeVal.Append("</cell>");

                strTreeVal.Append("<cell>");
                strTreeVal.Append(intChildRight.ToString());
                strTreeVal.Append("</cell>");

                strTreeVal.Append("<cell>");
                if (lsDepartTree[idxCnt].ChildProperty == 500 || lsDepartTree[idxCnt].ChildProperty == 600)
                    strTreeVal.Append("true");
                else
                    strTreeVal.Append("false");
                strTreeVal.Append("</cell>");

                strTreeVal.Append("<cell>");
                strTreeVal.Append("false");
                strTreeVal.Append("</cell>");

                strTreeVal.Append("</row>");
            }
        }
        strTreeVal.Append("</rows>");
        context.Response.ContentType = "text/xml";
        context.Response.Write(strTreeVal.ToString());
    }

    //当前部门信息
    public void getDepartInfo(HttpContext context)
    {
        string strDepartId = context.Request.Params["id"];

        try
        {
            string strKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, strDepartId);
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo entDepartInfo;
            entDepartInfo = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strKey);
            if (!cs.Hit)
            {
                Chenxin.Lib.Hr.BLL.Hr_DepartmentInfo bllDepartInfo = new Chenxin.Lib.Hr.BLL.Hr_DepartmentInfo();
                entDepartInfo =bllDepartInfo.GetModel(new Guid(strDepartId));
                if (entDepartInfo != null) cs.Set(strKey, entDepartInfo);
            }
            context.Response.Write(JsonHelper<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>.WriteObject("SUCCESS", entDepartInfo));
        }
        catch (Exception ex)
        {
            context.Response.Write(JsonHelper<string>.WriteObject("ERROR", ex.Message));
        }
    }

    //修改部门信息
    public void editDepart(HttpContext context)
    {
        try
        {
            string Id = context.Request.Params["Id"];
            string Property = string.IsNullOrEmpty(context.Request.Params["DepartProperty"]) ? "" : context.Request.Params["DepartProperty"];
            
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo dep = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(new Guid(Id));

            string strCacheKey = "";
            
            //修改商圈或分类
            if (Property == "300" || Property == "400")
            {
                string strSql = string.Format("update Hr_DepartmentInfo set DepartName='{0}' where DepartId='{1}';", context.Request.Params["DepartName"], Id);

                Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);

                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo depart = new Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo();
                dep.DepartId =new Guid(Id);
                dep.DepartName = context.Request.Params["DepartName"];
                //添加操作日志
                AddUserLogs(int.Parse(Property), depart, "update");

                //删除公司下商圈分类的缓存
                strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_STRUCT_TREE, dep.CompanyId + ".4000");
                cs.Delete(strCacheKey);
                
                context.Response.Write(JsonHelper<string>.WriteObject("SUCCESS", ""));
            }
            //修改部门信息
            else
            {                
                dep.DepartName = context.Request.Params["DepartName"];
                dep.DepartKind = context.Request.Params["DepartKind"];
                dep.Region = context.Request.Params["Region"];
                dep.Tel = context.Request.Params["Tel"];
                dep.Address = context.Request.Params["Address"];
                dep.Email = context.Request.Params["Email"];
                dep.RegionCtr = string.IsNullOrEmpty(context.Request.Params["RegionCtr"]) ? "" : context.Request.Params["RegionCtr"];
                dep.IsOpen = bool.Parse(context.Request.Params["IsOpen"]);
                dep.IsCalculate = bool.Parse(context.Request.Params["IsCalculate"]);
                dep.IsContractCenter = bool.Parse(context.Request.Params["IsContractCenter"]);

                //修改部门参数
                DepOperation(context, "update", Id);
                
                Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.Update(dep);
                //添加操作日志
                AddUserLogs(int.Parse(Property), dep, "update");

                string strSql = string.Format("ChildId='{0}'", Id.ToString());
                List<Chenxin.Lib.Hr.Entity.Hr_Struct_DepartTreeRelation> list = Chenxin.Lib.Hr.DAL.Hr_Struct_DepartTreeRelation.GetListArray(strSql);
                if (list.Count > 0)
                {
                    Guid parentId = list[0].ParentId;
                    //删除组织结构 商圈部门 缓存
                    strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_STRUCT_TREE, parentId);
                    cs.Delete(strCacheKey);
                }              
                
                context.Response.Write(JsonHelper<string>.WriteObject("SUCCESS", ""));
            }

            //删除部门信息缓存
            strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, Id);
            cs.Delete(strCacheKey);
            
            //删除部门设定缓存
            strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPART_SETTINGS, Id);
            cs.Delete(strCacheKey);
        }
        catch (Exception ex)
        {
            context.Response.Write(JsonHelper<string>.WriteObject("ERROR", ex.Message));
        }
    }

    //查询是否有子节点及隶属的人员
    public void hasChildDepart(HttpContext context)
    {
        //hejifeng 010406 Add Start
        string strRet;
        //hejifeng 010406 Add End
        try
        {
            string strDepartId = context.Request.Params["Id"];
            string strSql = string.Format("select acount+bcount from (select count(*) as acount from Struct_UserDepartRelation where DepartId='{0}' and IsBelong='true')a,(select count(*) as bcount from Hr_Struct_DepartTreeRelation where ParentId='{1}')b", strDepartId, strDepartId);
            bool flag = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.SearchSQL(strSql);

            StringBuilder output = new StringBuilder();

            //hejifeng 010406 Modify Start
            //if (!flag)
            //    output.Append("{success:\"1\"}");
            //else
            //    output.Append("{success:\"0\"}");
            //context.Response.Write(output);

            strRet = retExecResult(Constants.ExecResult.Succ, "", flag);
            context.Response.Write(strRet);
            //hejifeng 010406 Modify End
        }
        catch (Exception ex)
        {
            //hejifeng 010406 Add Start
            strRet = retExecResult(Constants.ExecResult.Error, ex.Message, "");
            context.Response.Write(strRet);
            //hejifeng 010406 Add End
        }
    }

    //删除节点 
    public void delDepart(HttpContext context)
    {
        string strDepartId = context.Request.Params["DeaprtId"];
        string Property = context.Request.Params["Property"];
        string DepName = context.Request.Params["depname"];
        
        Chenxin.Lib.Hr.BLL.OrganizationManage bllOrgManage = new Chenxin.Lib.Hr.BLL.OrganizationManage();
        try
        {
            if (Property == "100")
            {
                string strSql = string.Format("delete Struct_CityBaseInfo where CityId='{0}'", strDepartId);
                Chenxin.Lib.Passport.DAL.Hr_UserInfo.ExecuteSQL(strSql);

                //删除城市缓存                
                string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_CITYS);
                cs.Delete(strCacheKey); 
            }
            //删除节点关系及节点信息、缓存
            bllOrgManage.DeleteLeaf(new Guid(strDepartId));

            //删除部门设定缓存
            if (Property == "500" || Property == "600")
            {
                string strCacheKey_setting = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPART_SETTINGS, strDepartId);
                cs.Delete(strCacheKey_setting);
            }
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo dep = new Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo();
            dep.DepartName = DepName;
            dep.DepartId = new Guid(strDepartId);
            //添加操作日志
            AddUserLogs(int.Parse(Property), dep, "del");
            
            context.Response.Write("{success:\"1\"}");
        }
        catch (Exception ex)
        {
            context.Response.Write("{success:\"0\",txt:\"" + ex.Message + "\"}");
        }
    }

    //根据部门ID得到该部门的人员权限信息
    public void getUsersInfo(HttpContext context)
    {
        //参数列表
        System.Collections.Hashtable htParams = new System.Collections.Hashtable();
        //当前参数
        string strParam;
        //一页所显示的条数
        int intShowRows = 0;
        //当前页码
        int intCurPage = 0;
        //总记录数
        int intTotalCnt = 0;


        //当前页数
        strParam = context.Request.Params["page"];
        if (strParam != null & strParam != "")
        {
            intCurPage = Convert.ToInt32(strParam);
            htParams.Add("page", strParam);
        }
        //显示行数
        strParam = context.Request.Params["rows"];
        if (strParam != null & strParam != "")
        {
            intShowRows = Convert.ToInt32(strParam);
            htParams.Add("rows", strParam);
        }
        //排序项目
        strParam = context.Request.Params["sidx"];
        if (strParam != null & strParam != "")
        {
            htParams.Add("sidx", strParam);
        }
        //排序类型
        strParam = context.Request.Params["sord"];
        if (strParam != null & strParam != "")
        {
            htParams.Add("sord", strParam);
        }

        //当前部门ID
        strParam = context.Request.Params["strwhere"];
        if (strParam != null & strParam != "")
        {
            htParams.Add("strwhere", strParam);
        }

        Chenxin.Lib.Hr.BLL.Struct_UserDepartRelation bllStruce = new Chenxin.Lib.Hr.BLL.Struct_UserDepartRelation();

        DataSet dsUserInfo = bllStruce.GetUserByDepartId(htParams);

        intTotalCnt = (int)dsUserInfo.Tables[1].Rows[0][0];

        context.Response.Write(GetJson(dsUserInfo.Tables[0], intShowRows, intCurPage, intTotalCnt));
    }

    //*******************************************
    //功能概要       ：转化为jqGrid的数据格式
    //参数説明       ：dtData 要转化的原始数据
    //               ：intShowRows 一页所要显示的条数
    //               ：intCurPage 当前的页码
    //               ：intTotal 数据总条数
    //返回值説明     ：无
    //功能詳細       ：转化为jqGrid的数据格式
    //作成者         ：he.jifeng 
    //作成日         ：2010-03-07 
    //*******************************************
    public string GetJson(DataTable dtData, double intShowRows, int intCurPage, int intTotal)
    {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("{\"page\":" + intCurPage + ",\"total\":" + Math.Ceiling(intTotal / intShowRows) + ",\"records\":" + intTotal + ",\"rows\"");
        jsonBuilder.Append(":[");
        for (int i = 0; i < dtData.Rows.Count; i++)
        {
            jsonBuilder.Append("{\"id\":\"" + dtData.Rows[i]["UserId"].ToString() + "\",\"cell\":[\"\",");

            for (int j = 1; j < dtData.Columns.Count; j++)
            {
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dtData.Rows[i][j].ToString());
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]},");
        }
        if (dtData.Rows.Count > 0)
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
        jsonBuilder.Append("}");
        return jsonBuilder.ToString();
    }

    //重置密码方法
    public void resetPassword(HttpContext context)
    {
        string strUserId = context.Request.Params["UserId"];
        string strNewPwd = context.Request.Params["newpwd"];

        Chenxin.Lib.Passport.BLL.Hr_UserInfo bllUserInfo = new Chenxin.Lib.Passport.BLL.Hr_UserInfo();

        try
        {
            bllUserInfo.ResetPassword(new Guid(strUserId), strNewPwd);
            context.Response.Write(retExecResult(Constants.ExecResult.Succ, "", ""));
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }



    //名称验证
    private void NameCheck(HttpContext context)
    {
        //子类型（城市、公司、商圈、门店）
        string stype = "";
        string strwhere = "";
        //节点名字
        string name = "";
        //父节点ID
        string parentid = "";
        //类型INT值
        string property = "";

        StringBuilder output = new StringBuilder();

        if (!string.IsNullOrEmpty(context.Request.QueryString["stype"]))
        {
            stype = context.Request.QueryString["stype"];
        }
        switch (stype)
        {

            case "city":
                string cityname = "";
                if (!string.IsNullOrEmpty(context.Request.QueryString["txtCityName"]))
                {
                    cityname = context.Request.QueryString["txtCityName"];
                }
                strwhere = String.Format("DepartName='{0}' and DepartProperty=100", cityname);

                break;
            case "company":
                if (!string.IsNullOrEmpty(context.Request.QueryString["name"]))
                {
                    name = context.Request.QueryString["name"];
                } if (!string.IsNullOrEmpty(context.Request.QueryString["parentid"]))
                {
                    parentid = context.Request.QueryString["parentid"];
                }
                strwhere = String.Format("DepartName='{0}' and DepartProperty=200 and CityId='{1}'", name, parentid);

                break;
            case "group":
                if (!string.IsNullOrEmpty(context.Request.QueryString["property"]))
                {
                    property = context.Request.QueryString["property"];
                }
                if (!string.IsNullOrEmpty(context.Request.QueryString["name"]))
                {
                    name = context.Request.QueryString["name"];
                }
                if (!string.IsNullOrEmpty(context.Request.QueryString["parentid"]))
                {
                    parentid = context.Request.QueryString["parentid"];
                }
                if (!string.IsNullOrEmpty(context.Request.QueryString["subop"]))
                    strwhere = String.Format("DepartName='{0}' and DepartProperty={1} and CompanyId=(select CompanyId from Hr_DepartmentInfo where DepartId='{2}') and DepartId<>'{3}'", name, property, parentid, parentid);
                else
                    strwhere = String.Format("DepartName='{0}' and DepartProperty={1} and CompanyId=(select CompanyId from Hr_DepartmentInfo where DepartId='{2}')", name, property, parentid);
                break;
            case "dep":
                goto case "group";
        }

        DataSet ds = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetList(strwhere);
        if (ds.Tables[0].Rows.Count > 0)
            output.Append("{success:\"0\"}");
        else
            output.Append("{success:\"1\"}");
        context.Response.Write(output);
    }

    //编号验证
    private void CodeCheck(HttpContext context)
    {
        //子类型（城市、公司、商圈、门店）
        string stype = "";
        string strwhere = "";
        //节点编号
        string code = "";
        //父节点ID
        string parentid = "";
        //类型INT值
        string property = "";

        StringBuilder output = new StringBuilder();

        if (!string.IsNullOrEmpty(context.Request.QueryString["stype"]))
        {
            stype = context.Request.QueryString["stype"];
        }
        switch (stype)
        {

            case "city":
                string citycode = "";
                if (!string.IsNullOrEmpty(context.Request.QueryString["txtCityCode"]))
                {
                    citycode = context.Request.QueryString["txtCityCode"];
                }
                strwhere = String.Format("DepartCode='{0}' and DepartProperty=100", citycode);

                break;
            case "company":
                if (!string.IsNullOrEmpty(context.Request.QueryString["code"]))
                {
                    code = context.Request.QueryString["code"];
                } if (!string.IsNullOrEmpty(context.Request.QueryString["parentid"]))
                {
                    parentid = context.Request.QueryString["parentid"];
                }
                strwhere = String.Format("DepartCode='{0}' and DepartProperty=200 and CityId='{1}'", code, parentid);

                break;
            case "group":

                if (!string.IsNullOrEmpty(context.Request.QueryString["property"]))
                {
                    property = context.Request.QueryString["property"];
                }
                if (!string.IsNullOrEmpty(context.Request.QueryString["code"]))
                {
                    code = context.Request.QueryString["code"];
                }
                if (!string.IsNullOrEmpty(context.Request.QueryString["parentid"]))
                {
                    parentid = context.Request.QueryString["parentid"];
                }
                strwhere = String.Format("DepartCode='{0}' and DepartProperty={1} and CompanyId=(select CompanyId from Hr_DepartmentInfo where DepartId='{2}')", code, property, parentid);
                break;
            case "dep":
                goto case "group";
        }
        DataSet ds = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetList(strwhere);
        if (ds.Tables[0].Rows.Count > 0)
            output.Append("{success:\"0\"}");
        else
            output.Append("{success:\"1\"}");
        context.Response.Write(output);
    }

    //添加节点
    private void AddDep(HttpContext context)
    {
        Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo dep = new Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo();
        string ParentId = context.Request.Params["ParentId"];
        dep.DepartName = context.Request.Params["DepartName"];
        dep.DepartCode = context.Request.Params["DepartCode"];
        dep.DepartProperty = int.Parse(context.Request.Params["DepartProperty"]);
        dep.DepartId = Guid.NewGuid();
        Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo parentdep = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(new Guid(ParentId));
        switch (dep.DepartProperty)
        {
            //城市
            case 100:
                dep.CityId = dep.DepartId;
                dep.City = dep.DepartName;
                dep.DepartSrc = dep.DepartCode + "/";
                dep.IsOpen = true;
                break;
            //公司
            case 200:
                dep.City = parentdep.City;
                dep.CityId = parentdep.CityId;
                dep.CompanyId = dep.DepartId;
                dep.CompanyName = dep.DepartName;
                dep.DepartSrc = parentdep.DepartSrc + dep.DepartCode + "/";
                dep.IsOpen = true;
                break;
            //商圈
            case 300:
                dep.City = parentdep.City;
                dep.CityId = parentdep.CityId;
                dep.CompanyId = parentdep.CompanyId;
                dep.CompanyName = parentdep.CompanyName;
                dep.DepartSrc = parentdep.DepartSrc + dep.DepartCode + "/";
                dep.IsOpen = true;
                break;
            //分类
            case 400:
                dep.City = parentdep.City;
                dep.CityId = parentdep.CityId;
                dep.CompanyId = parentdep.CompanyId;
                dep.CompanyName = parentdep.CompanyName;
                dep.DepartSrc = parentdep.DepartSrc + dep.DepartCode + "/";
                dep.IsOpen = true;
                break;
            //部门
            case 500:
                dep.City = parentdep.City;
                dep.CityId = parentdep.CityId;
                dep.CompanyId = parentdep.CompanyId;
                dep.CompanyName = parentdep.CompanyName;
                dep.DepartKind = context.Request.Params["DepartKind"];
                dep.Region = context.Request.Params["Region"];
                dep.Tel = context.Request.Params["Tel"];
                dep.Address = context.Request.Params["Address"];
                dep.Email = context.Request.Params["Email"];
                dep.RegionCtr = context.Request.Params["RegionCtr"];
                dep.IsOpen = bool.Parse(context.Request.Params["IsOpen"]);
                dep.IsCalculate = bool.Parse(context.Request.Params["IsCalculate"]);
                dep.IsContractCenter = bool.Parse(context.Request.Params["IsContractCenter"]);
                dep.DepartSrc = parentdep.DepartSrc + dep.DepartCode;

                DepOperation(context, "add", dep.DepartId.ToString());

                string strSql = string.Format("insert into HR_Rel_Purview select newid(),'{0}',TermsName,ViewPubHouse,ViewPrivHouse,ViewHideHouse,ViewPubDemand,ViewPrivDemand,ViewRealCustomer,ViewFakeCustomer,EditPrimaryHouse,EditNormalHouse,EditCustomer,DelTrace,CanProtect,CanLockHouse,ViewLockHouse,CanChangeApp,ViewChange,CanChangeConfirm,ViewEntrust,CanCancelTrust,UnCancelTrust,CanDelTrust,CanDoTask,getdate() from HR_Rel_Purview where DepartID='{1}';", dep.DepartId.ToString(), dep.CompanyId.ToString());
                Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);
                break;

            //其他部门
            case 600:
                goto case 500;

        }
        dep.AddPerson = CurrentUserInfo.UserName;
        dep.AddTime = DateTime.Now;
        Chenxin.Lib.Hr.BLL.OrganizationManage bllOrgManage = new Chenxin.Lib.Hr.BLL.OrganizationManage();
        try
        {
            bllOrgManage.AddSubTree(new Guid(ParentId), dep);
            
            string strCacheKey = "";
            if (dep.DepartProperty == 100)
            {
                Chenxin.Lib.Hr.Entity.Struct_CityBaseInfo cityinfo = new Chenxin.Lib.Hr.Entity.Struct_CityBaseInfo();
                cityinfo.CityId = dep.DepartId;
                cityinfo.CityCode = dep.DepartCode.ToUpper();
                cityinfo.CityName = dep.DepartName;
                Chenxin.Lib.Hr.DAL.Struct_CityBaseInfo.Add(cityinfo);
                
                //删除城市缓存                
                strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_CITYS);
                cs.Delete(strCacheKey);                
            }
            
            //添加日志
            AddUserLogs(dep.DepartProperty, dep,"add");            
            
            
            context.Response.Write(JsonHelper<string>.WriteObject("SUCCESS", ""));
        }
        catch (Exception ex)
        {
            context.Response.Write(JsonHelper<string>.WriteObject("ERROR", ex.Message));
        }
    }

    //添加日志操作
    private void AddUserLogs(int? property, Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo dep,string type)
    {
        //插入语句
        string strSql = "";
        if (type == "add")
            type = "添加";
        else if (type == "update")
            type = "编辑";
        else if (type == "del")
            type = "删除";
        
        switch (property)
        {
            case 100:
                strSql = string.Format("insert into Hr_UserLogs values(newid(),'{0}','{1}','{2}','{3}','{4}','{6}城市','{2}-{6}城市:{5}',getdate())", dep.DepartId.ToString(), CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, dep.DepartName,type);
                break;
            case 200:
                strSql = string.Format("insert into Hr_UserLogs values(newid(),'{0}','{1}','{2}','{3}','{4}','{6}公司','{2}-{6}公司:{5}',getdate())", dep.DepartId.ToString(), CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, dep.DepartName, type);
                break;
            case 300:
                strSql = string.Format("insert into Hr_UserLogs values(newid(),'{0}','{1}','{2}','{3}','{4}','{6}商圈','{2}-{6}商圈:{5}',getdate())", dep.DepartId.ToString(), CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, dep.DepartName, type);
                break;
            case 400:
                strSql = string.Format("insert into Hr_UserLogs values(newid(),'{0}','{1}','{2}','{3}','{4}','{6}分类','{2}-{6}分类:{5}',getdate())", dep.DepartId.ToString(), CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, dep.DepartName, type);
                break;
            case 500:
                strSql = string.Format("insert into Hr_UserLogs values(newid(),'{0}','{1}','{2}','{3}','{4}','{6}部门','{2}-{6}部门:{5}',getdate())", dep.DepartId.ToString(), CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, dep.DepartName, type);
                break;
            case 600:
                strSql = string.Format("insert into Hr_UserLogs values(newid(),'{0}','{1}','{2}','{3}','{4}','{6}其他部门','{2}-{6}其他部门:{5}',getdate())", dep.DepartId.ToString(), CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, dep.DepartName, type);
                break;
        }
        Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);
    }
    
    //部门参数操作
    private void DepOperation(HttpContext context, string optype, string DepartId)
    {
        string ViewOwnerNum = "",
                 IsHideHouse = "",
                 IsAloneUserCode = "",
                 ProtectedNum = "",
                 IsProtectMark = "",
                 AllowPrivHouse = "",
                 MarkProtectHours = "",
                 AllowPubDemand = "",
                 IsUseBlacklist = "",
                 Level = "",
                 LockHouseDay = "",
        CanAddAtCityId = "",
        CanAddAtCityName = "";

        if (!string.IsNullOrEmpty(context.Request.Params["OwnerNum"]))
        {
            ViewOwnerNum = context.Request.Params["OwnerNum"];
        }
        if (!string.IsNullOrEmpty(context.Request.Params["HdeHouse"]))
        {
            IsHideHouse = context.Request.Params["HdeHouse"];
        }
        if (!string.IsNullOrEmpty(context.Request.Params["AloneUserCode"]))
        {
            IsAloneUserCode = context.Request.Params["AloneUserCode"];
        }
        if (!string.IsNullOrEmpty(context.Request.Params["ProtectedNum"]))
        {
            ProtectedNum = context.Request.Params["ProtectedNum"];
        }
        if (!string.IsNullOrEmpty(context.Request.Params["IsProtectMark"]))
        {
            IsProtectMark = context.Request.Params["IsProtectMark"];
        }
        if (!string.IsNullOrEmpty(context.Request.Params["AllowPrivHouse"]))
        {
            AllowPrivHouse = context.Request.Params["AllowPrivHouse"];
        }
        if (!string.IsNullOrEmpty(context.Request.Params["MarkProtectHours"]))
        {
            MarkProtectHours = context.Request.Params["MarkProtectHours"];
        }
        if (!string.IsNullOrEmpty(context.Request.Params["AllowPubDemand"]))
        {
            AllowPubDemand = context.Request.Params["AllowPubDemand"];
        }

        if (!string.IsNullOrEmpty(context.Request.Params["IsUseBlacklist"]))
        {
            IsUseBlacklist = context.Request.Params["IsUseBlacklist"];
        }
        if (!string.IsNullOrEmpty(context.Request.Params["Level"]))
        {
            Level = context.Request.Params["Level"];
        }
        if (!string.IsNullOrEmpty(context.Request.Params["LockHouseDay"]))
        {
            LockHouseDay = context.Request.Params["LockHouseDay"];
        }
        if (!string.IsNullOrEmpty(context.Request.Params["CanAddAtCityId"]))
        {
            CanAddAtCityId = context.Request.Params["CanAddAtCityId"];
        }
        if (!string.IsNullOrEmpty(context.Request.Params["CanAddAtCityName"]))
        {
            CanAddAtCityName = context.Request.Params["CanAddAtCityName"];
        }


        string strSql = "";
        if (optype == "update")
        {
            strSql = @"update House_BusinessSetting set ProtectedNum='" + ProtectedNum + "',ViewOwnerNum='" + ViewOwnerNum + "',IsHideHouse='" + IsHideHouse + "',IsAloneUserCode='" + IsAloneUserCode + "',LockHouseDay='" + LockHouseDay + "',IsProtectMark='" + IsProtectMark + "',MarkProtectHours='" + MarkProtectHours + "',AllowPrivHouse='" + AllowPrivHouse + "',AllowPubDemand='" + AllowPubDemand + "',IsUseBlacklist='" + IsUseBlacklist + "',BlacklistLevel='" + Level + "',CanAddAtCityId='" + CanAddAtCityId + "',CanAddAtCityName='" + CanAddAtCityName + "' where DepartId='" + DepartId + "'; ";
        }
        else
        {
            strSql = @"insert into  House_BusinessSetting (DepartId,ProtectedNum,ViewOwnerNum,IsHideHouse,IsAloneUserCode,LockHouseDay,IsProtectMark,MarkProtectHours,AllowPrivHouse,AllowPubDemand,IsUseBlacklist,BlacklistLevel,CanAddAtCityId,CanAddAtCityName) 
                        values ('" + DepartId + "','" + ProtectedNum + "','" + ViewOwnerNum + "','" + IsHideHouse + "','" + IsAloneUserCode + "','" + LockHouseDay + "','" + IsProtectMark + "','" + MarkProtectHours + "','" + AllowPrivHouse + "','" + AllowPubDemand + "','" + IsUseBlacklist + "','" + Level + "','" + CanAddAtCityId + "','" + CanAddAtCityName + "'); ";
        }
        Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);
    }

    //得到下拉框数据
    private void initSelect(HttpContext context)
    {
        string stype = "";
        string strwhere = "";
        string id = "";
        if (!string.IsNullOrEmpty(context.Request.QueryString["stype"]))
        {
            stype = context.Request.QueryString["stype"];
        }
        if (!string.IsNullOrEmpty(context.Request.QueryString["id"]))
        {
            id = context.Request.QueryString["id"];
        }

        switch (stype)
        {
            case "city":
                strwhere = string.Format("DepartProperty=100");
                break;
            case "com":
                strwhere = string.Format("DepartProperty=200 and CityId='{0}'", id);
                break;
            case "dep":
                strwhere = string.Format("(DepartProperty=500 or DepartProperty=600) and CompanyId='{0}'", id);
                break;
            case "move":
                strwhere = string.Format("(DepartProperty=300 or DepartProperty=400) and CompanyId=(select CompanyId from Hr_DepartmentInfo where DepartId='{0}')", id);
                break;
        }


        System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo> depList = new System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>();
        if (stype != "move")
        {
            Chenxin.Lib.Cache.CacheService cs_hr = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HR);
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HR, stype + "." + id);
            depList = cs_hr.GetList<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCacheKey);

            if (!cs.Hit)//若缓存未命中，则从数据库中获取并存入缓存，时间为1天
            {
                depList = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetListArray(strwhere);

                cs_hr.Set(strCacheKey, depList, DateTime.Today.AddDays(1));
            }
        }
        else
            depList = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetListArray(strwhere);


        //生成JSON字符串
        System.Text.StringBuilder str = new System.Text.StringBuilder();

        foreach (Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item in depList)
        {
            str.Append(", { txt: '" + item.DepartName.Trim() + "', val: '" + item.DepartId.ToString().Trim() + "' }");
        }

        context.Response.Write(str.ToString());
    }

    //添加人员
    private void addUser(HttpContext context)
    {
        string strRet;
        try
        {
            string stype = "";
            string todepid = "";    //目标门店ID
            string todepname = "";  //目标门店名称
            string depid = "";  //源对象
            string strSql = "";
            string qx = "";     //选中的权限 （列名）

            if (!string.IsNullOrEmpty(context.Request.Params["stype"]))
            {
                stype = context.Request.Params["stype"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["depid"]))
            {
                depid = context.Request.Params["depid"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["todepid"]))
            {
                todepid = context.Request.Params["todepid"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["todepname"]))
            {
                todepname = context.Request.Params["todepname"];
            }
            if (!string.IsNullOrEmpty(context.Request.Params["qx"]))
            {
                qx = context.Request.Params["qx"];
            }

            string str_qx = "";
            string[] array = qx.Split(',');
            for (int i = 0; i < array.Length; i++)
            {
                str_qx += "'1',";
            }

            //快捷设定
            if (stype == "faster")
            {
                if (depid != todepid)
                {
                    strSql += string.Format("DELETE Struct_UserDepartRelation WHERE exists (select userid from hr_userinfo where BelongDepartId='{0}' and userid=Struct_UserDepartRelation.userid) and DepartId='{1}' and IsBelong='false';", depid, todepid);
                    strSql += string.Format("insert into Struct_UserDepartRelation(RecordId,DepartId,DepartName,UserId,UserCode,UserName,IsBelong,{0},Addtime) select newid(),'{1}','{2}',UserId,UserCode,UserName,'0',{3},getdate() from Hr_UserInfo where not exists (select UserId from Struct_UserDepartRelation where DepartId='{4}' and userid=Hr_UserInfo.userid) and DepartId='{5}';", qx, todepid, todepname, str_qx.Substring(0, str_qx.Length - 1), todepid, depid);
                }
                else
                {
                    strSql += string.Format("delete Struct_UserDepartRelation where exists(select userid from hr_userinfo where BelongDepartId='{0}' and userid=Struct_UserDepartRelation.userid) and DepartId='{1}' and IsBelong='true';", depid, todepid);
                    strSql += string.Format("insert into Struct_UserDepartRelation(RecordId,DepartId,DepartName,UserId,UserCode,UserName,IsBelong,{0},Addtime) select newid(),'{1}','{2}',UserId,UserCode,UserName,'1',{3},getdate() from Hr_UserInfo where DepartId='{4}' and Status='1' and IsVirtual='False';", qx, todepid, todepname, str_qx.Substring(0, str_qx.Length - 1), depid);
                }
            }
            //手动设定
            else
            {
                string role = "";   //选中的角色    （角色id）
                if (!string.IsNullOrEmpty(context.Request.Params["role"]))
                {
                    role = context.Request.Params["role"];
                }
                string[] todepid_array = todepid.Replace("'", "").Split(',');
                string[] todepname_array = todepname.Split(',');

                //手动—部门
                if (depid.Length > 0)
                {
                    strSql += string.Format("DELETE Struct_UserDepartRelation WHERE exists (select userid from hr_userinfo where BelongDepartId='{0}' and userid=Struct_UserDepartRelation.userid) and DepartId in ({1});", depid, todepid);
                    for (int i = 0; i < todepid_array.Length; i++)
                    {
                        if (depid != todepid_array[i])
                            strSql += string.Format("insert into Struct_UserDepartRelation(RecordId,DepartId,DepartName,UserId,UserCode,UserName,IsBelong,{0},Addtime) select newid(),'{1}','{2}',UserId,UserCode,UserName,'0',{3},getdate() from Hr_UserInfo where not exists (select UserId from Struct_UserDepartRelation where DepartId='{4}' and userid=Hr_UserInfo.userid) and BelongDepartId='{5}';", qx, todepid_array[i], todepname_array[i], str_qx.Substring(0, str_qx.Length - 1), todepid_array[i], depid);
                        else
                            strSql += string.Format("insert into Struct_UserDepartRelation(RecordId,DepartId,DepartName,UserId,UserCode,UserName,IsBelong,{0},Addtime) select newid(),'{1}','{2}',UserId,UserCode,UserName,'1',{3},getdate() from Hr_UserInfo where BelongDepartId='{4}' and Status='1' and IsVirtual='False';", qx, todepid_array[i], todepname_array[i], str_qx.Substring(0, str_qx.Length - 1), depid);
                    }
                }
                //手动—员工
                else
                {
                    string usercode = context.Request.Params["codeid"];
                    strSql += string.Format("delete Struct_UserDepartRelation where UserCode='{0}' and DepartId in ({1});", usercode, todepid);
                    for (int i = 0; i < todepid_array.Length; i++)
                    {
                        strSql += string.Format("insert into Struct_UserDepartRelation(RecordId,DepartId,DepartName,UserId,UserCode,UserName,IsBelong,{0},Addtime) select newid(),'{1}','{2}',UserId,UserCode,UserName,case (select 1 from hr_userinfo where BelongDepartId='{3}' and usercode='{4}' ) when 1 then 1 else 0 end,{5},getdate() from Hr_UserInfo where UserCode='{6}';", qx, todepid_array[i], todepname_array[i], todepid_array[i], usercode, str_qx.Substring(0, str_qx.Length - 1), usercode);
                    }
                    //如有角色，则进行角色的修改

                    if (role.Length > 0)
                    {
                        strSql += string.Format("delete Base_RoleUserRelationInfo where UserId=(select UserId from Hr_UserInfo where UserCode='{0}');", usercode);
                        string[] role_array = role.Split(',');
                        for (int i = 0; i < role_array.Length; i++)
                        {
                            strSql += string.Format("insert into Base_RoleUserRelationInfo select newid(),'{0}',UserId from Hr_UserInfo where UserCode='{1}';", role_array[i], usercode);
                        }
                    }
                }
            }

            bool flag = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);


            System.Text.StringBuilder str = new System.Text.StringBuilder();
            //hejifeng 010406 Modify Start
            //if (flag)
            //    str.Append("{success:'1'}");
            //else
            //    str.Append("{success:'0',txt:'没有可添加的人员！'}");
            //context.Response.Write(str.ToString());

            if (flag)
            {
                strRet = retExecResult(Constants.ExecResult.Succ, "", true);
            }
            else
            {
                strRet = retExecResult(Constants.ExecResult.Succ, "没有可添加的人员", false);
            }
            context.Response.Write(strRet);
            //hejifeng 010406 Modify End
        }
        catch (Exception ex)
        {
            //hejifeng 010406 Add Start
            strRet = retExecResult(Constants.ExecResult.Error, ex.Message, "");
            context.Response.Write(strRet);
            //hejifeng 010406 Add End
        }
    }

    //查询人员总数
    private void searchDep(HttpContext context)
    {
        string strwhere = "";
        string companyid = "";
        if (!string.IsNullOrEmpty(context.Request.QueryString["companyid"]))
        {
            companyid = context.Request.QueryString["companyid"];
        }
        strwhere = string.Format("CompanyId='{0}' and (DepartProperty=500 or DepartProperty=600)", companyid);
        DataSet ds = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetList(1, 1, "DepartId", "Hr_DepartmentInfo", strwhere, "*", "*", true);

        System.Text.StringBuilder str = new System.Text.StringBuilder();
        str.Append("{count:'" + ds.Tables[1].Rows[0][0].ToString() + "'}");
        context.Response.Write(str.ToString());
    }

    //分页显示
    private void pageShow(HttpContext context)
    {
        int pageindex = 0;//页码
        int PageSize = 0;//页显示行数
        string strwhere = "";
        //页码        
        if (!string.IsNullOrEmpty(context.Request.QueryString["pageIndex"]))
        {
            pageindex = int.Parse(context.Request.QueryString["pageIndex"]) + 1;
        }
        //页显示行数
        if (!string.IsNullOrEmpty(context.Request.QueryString["pageRow"]))
        {
            PageSize = int.Parse(context.Request.QueryString["pageRow"]);
        }
        string companyid = "";
        if (!string.IsNullOrEmpty(context.Request.QueryString["companyid"]))
        {
            companyid = context.Request.QueryString["companyid"];
        }
        strwhere = string.Format("CompanyId='{0}' and (DepartProperty=500 or DepartProperty=600)", companyid);
        DataSet ds = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetList(pageindex, PageSize, "DepartId", "Hr_DepartmentInfo", strwhere, "DepartId,DepartName", "DepartId,DepartName", true);

        System.Text.StringBuilder str = new System.Text.StringBuilder();
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            string td = "";
            td = String.Format("<span><input type='checkbox' value='{0}' name='{1}' />{2}</span>", ds.Tables[0].Rows[i][0], ds.Tables[0].Rows[i][1], ds.Tables[0].Rows[i][1]);
            str.Append(td);
        }
        context.Response.Write(str.ToString());
    }

    //删除人员
    private void delUser(HttpContext context)
    {
        try
        {
            string userid = "";
            if (!string.IsNullOrEmpty(context.Request.Params["userid"]))
            {
                userid = context.Request.Params["userid"];
            }
            string strSql = string.Format("delete Struct_UserDepartRelation where userid='{0}'", userid);

            bool flag = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);


            System.Text.StringBuilder str = new System.Text.StringBuilder();

            //if (flag)
            //    str.Append("{success:'1'}");
            //else
            //    str.Append("{success:'0',txt:'操作失败!'}");
            //context.Response.Write(str.ToString());

            context.Response.Write(retExecResult(Constants.ExecResult.Succ, "", ""));
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }
}